package main

import (
	"fmt"
	"os"
	"strconv"
	"strings"
)

type MemoryInfo struct {
	Total   uint64  //总内存
	Used    uint64  //已用内存
	UsedPct float64 //使用率
}

// 获取内存信息
func Getmemory() (MemoryInfo, error) {
	var info MemoryInfo
	content, err := os.ReadFile("/proc/meminfo")
	if err != nil {
		return info, fmt.Errorf("读取文件失败，原因为：%s", err)
	}
	lines := strings.Split(string(content), "\n")
	var memTotal, memAvailable uint64
	for _, line := range lines {
		parts := strings.Fields(line)
		if len(parts) < 2 {
			continue
		}
		switch parts[0] {
		case "MemTotal:":
			memTotal, _ = strconv.ParseUint(parts[1], 10, 64)
		case "MemAvailable:":
			memAvailable, _ = strconv.ParseUint(parts[1], 10, 64)
		}

	}
	info.Total = memTotal
	info.Used = memTotal - memAvailable
	info.UsedPct = float64(info.Used) / float64(info.Total) * 100
	return info, nil
}
